package cosw.com.shanghaica;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.InputFilter;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cosw.sdkShanghaiCA.EnumError;
import com.cosw.sdkShanghaiCA.SHCAProvider;
import com.cosw.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cosw.com.shanghaica.util.Constant;

public class ContainerActivity extends ActionBarActivity {

    @BindView(R.id.btn_generate_key)
    Button btn_generate_key;
    @BindView(R.id.btn_show_certificate)
    Button btnShowCertificate;
    @BindView(R.id.btn_import_certificate)
    Button btnImportCertificate;
    @BindView(R.id.btn_export_certificate)
    Button btnExportCertificate;
    @BindView(R.id.btn_export_public_key)
    Button btnExportPublicKey;
    @BindView(R.id.btn_reset_pin)
    Button btnResetPwd;
    @BindView(R.id.btn_unblock_container)
    Button btnUnblockContainer;
    @BindView(R.id.btn_delete_container)
    Button btnDeleteContainer;
    @BindView(R.id.btn_sign)
    Button btnSign;
    @BindView(R.id.btn_encrypt)
    Button btnEncrypt;
    @BindView(R.id.btn_decrypt)
    Button btnDecrypt;

    private SHCAProvider provider;
    private Context mContext;

    private EditText et_input;
    private EditText et_input1;
    private String containerName;
    public byte[] indataforEn = new byte[(short)0x80];
    public String Endata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_container);
        ButterKnife.bind(this);

        mContext = this;

        containerName = getIntent().getStringExtra(Constant.EXTRA_KEY_CONTAINER_NAME);

        provider = SHCAProvider.getInstance(this.getApplication());
        StringUtil.arrayFillWithBytes(indataforEn,0,indataforEn.length,(byte)0x22);
    }

    public void showDialogMessage(String title, String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title).setMessage(msg).setPositiveButton("确定", null)
                .show();
    }

    @OnClick(R.id.btn_generate_key)
    public void onGenerateKeyClicked() {
        et_input = new EditText(mContext);
        et_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        et_input.setHint("请输入密码");
        et_input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et_input)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        int resCode = provider.generateKeyPair(containerName, 0x01, et_input.getText().toString().trim());
                        if (resCode == EnumError.SUCCESS.getResCode()) {
                            Toast.makeText(mContext, "生成密钥成功", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, "生成密钥失败失败 ", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    @OnClick(R.id.btn_show_certificate)
    public void onBtnShowCertificateClicked() {
        Intent intent = new Intent(this, CetifiacteInfoActivity.class);
        startActivity(intent);
    }

    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    @OnClick(R.id.btn_import_certificate)
    public void onBtnImportCertificateClicked() {
        //Intent intent = new Intent(this, ImportCertificateActivity.class);
        //startActivity(intent);

        et_input = new EditText(mContext);
        et_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        et_input.setHint("请输入密码");
        et_input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);

        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et_input)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        InputStream abpath = getClass().getResourceAsStream(
                                "/assets/hainanca.cer");

                        byte[] cert;
                        try {
                            cert = InputStreamToByte(abpath);
                            int res = provider.importCertificate(containerName, 2, cert, et_input.getText().toString().trim());

                            if (res == 1) {
                                Toast.makeText(mContext, "导入成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "导入失败！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    @OnClick(R.id.btn_export_certificate)
    public void onBtnExportCertificateClicked() {
        //Toast.makeText(this, "onBtnExportCertificateClicked", Toast.LENGTH_SHORT).show();

        byte[] res = provider.exportCertificate(containerName, (byte) 0x02);

        Log.e("exportCertification", StringUtil.byteArrayToHexString(res));
        if (res != null) {
            showDialogMessage("导出证书", StringUtil.byteArrayToHexString(res));
        } else {
            Toast.makeText(mContext, "导出证书失败！", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.btn_export_public_key)
    public void onBtnExportPublicKeyClicked() {
        byte[] res = provider.exportPubKey(containerName, 0x01);
        Log.e("exportPublicKey", StringUtil.byteArrayToHexString(res));
        if (res != null) {
            showDialogMessage("导出公钥", StringUtil.byteArrayToHexString(res));
        } else {
            Toast.makeText(mContext, "导出公钥失败！", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.btn_reset_pin)
    public void onBtnResetPwdClicked() {
        Intent intent = new Intent(this, ResetUserPinActivity.class);
        intent.putExtra("name", containerName);
        startActivity(intent);
    }

    @OnClick(R.id.btn_unblock_container)
    public void onBtnUnblockContainerClicked() {
        et_input = new EditText(mContext);
        et_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        et_input.setHint("请输入管理员密码");
        et_input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et_input)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        et_input1 = new EditText(mContext);
                        et_input1.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
                        et_input1.setHint("请输入用户密码");
                        et_input1.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                                .setView(et_input1)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        int res = provider.unLockDevice(containerName, et_input.getText().toString().trim(), et_input1.getText().toString().trim());
                                        if (res == EnumError.SUCCESS.getResCode()) {
                                            Toast.makeText(mContext, "容器解锁成功", Toast.LENGTH_LONG).show();
                                        } else {
                                            Toast.makeText(mContext, "容器解锁失败 ", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                }).setNegativeButton("取消", null).show();

                    }
                }).setNegativeButton("取消", null).show();
        // Toast.makeText(this, "onBtnUnblockContainerClicked", Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.btn_delete_container)
    public void onBtnDeleteContainerClicked() {
        et_input = new EditText(mContext);
        et_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        et_input.setHint("请输入密码");
        et_input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et_input)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        int res = provider.deleteContainer(containerName, et_input.getText().toString().trim());
                        if (res == EnumError.SUCCESS.getResCode()) {
                            Intent intent = new Intent(ContainerActivity.this, DeviceManageActivity.class);
                            startActivity(intent);
                            Toast.makeText(mContext, "删除容器成功", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mContext, "删除容器失败 ", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    @OnClick(R.id.btn_sign)
    public void onBtnSignClicked() {
        byte[] res = provider.exportPubKey(containerName, 0x01);
        Log.e("exportPublicKey", StringUtil.byteArrayToHexString(res));
        if (res != null) {
            Intent intent = new Intent(this, SignActivity.class);
            intent.putExtra("pubkey", provider.Pubkey);
            intent.putExtra("name", containerName);
            startActivity(intent);
        } else {
            Toast.makeText(mContext, "导出公钥失败！", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.btn_encrypt)
    public void onBtnEncryptClicked() {
        et_input = new EditText(mContext);
        et_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        et_input.setHint("请输入密码");
        et_input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et_input)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        byte[] res = provider.pubKeyEncryption(containerName,1,indataforEn,et_input.getText().toString().trim());
                        Endata = StringUtil.byteArrayToHexString(res);
                        if (res != null) {
                            showDialogMessage("加密结果", Endata);
                        } else {
                            Toast.makeText(mContext, "加密失败 ", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    @OnClick(R.id.btn_decrypt)
    public void onBtnDecryptClicked() {
        et_input = new EditText(mContext);
        et_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        et_input.setHint("请输入密码");
        et_input.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle("请输入PIN").setIcon(android.R.drawable.ic_dialog_info)
                .setView(et_input)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        byte[] res = provider.priKeyDecryption(containerName,1,StringUtil.hexStringToByteArray(Endata),et_input.getText().toString().trim());
                        if (res != null) {
                            showDialogMessage("解密结果", StringUtil.byteArrayToHexString(res));
                        } else {
                            Toast.makeText(mContext, "解密失败 ", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }
}
